/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entity.Question;
import entity.Questions;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 *
 * @author wei
 */
@ManagedBean(name = "questionFeed")
@SessionScoped
public class QuestionFeed extends LoginBacking implements Serializable {

    final String baseUrl = "http://api.stackoverflow.com/1.1/users/";
    List<Questions> questions = new ArrayList<Questions>();

    public List<Questions> getQuestions() {
        if(questions.isEmpty() && isUserLoggedIn())
            refreshFeed();
        return questions;
    }
    
    public void refreshFeed() {
        System.out.println("getting questions for user: " + getUser().toString());
        try {
            String targets = URLEncoder.encode(getUser().getFollowingToString(), "UTF-8");
            String url = baseUrl + targets + "/questions?sort=creation";
            System.out.println(url);
            URL request = new URL(url);           
            GZIPInputStream zipin = new GZIPInputStream(request.openStream());
            ObjectMapper mapper = new ObjectMapper();           
            Question question = mapper.readValue(zipin, Question.class);
            
            questions = question.getQuestions();
            
        } catch (JsonParseException ex) {
            ex.printStackTrace();
        } catch (JsonMappingException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void setQuestions(List<Questions> questions) {
        this.questions = questions;
    }
}
